<template>
  <view class="login-container">
    <!-- 标题区域 -->
    <view class="title-area">
      <text class="main-title" style="font-size: 2rem;">智慧大棚环境监控系统</text>
      <!--<text class="sub-title" style="font-size: 1rem;">走进智慧农业，创建幸福生活</text>-->
    </view>

    <!-- 登录表单区域 -->
    <view class="login-form-container">
      <!-- 登录方式选项卡 -->
      <view class="login-tabs">
        <view
          class="tab-item"
          :class="{ active: activeTab === 'account' }"
          @click="switchTab('account')"
        >
          登录
        </view>
        <view
          class="tab-item"
          :class="{ active: activeTab === 'mobile' }"
          @click="switchTab('mobile')"
        >
          注册
        </view>
      </view>

      <!-- 登录表单 -->
      <view v-if="activeTab === 'account'" class="login-form">
        <!-- 错误信息显示 -->
        <view v-if="loginErrorMessage" class="error-message">
          <text class="error-text">{{ loginErrorMessage }}</text>
        </view>

        <uni-easyinput
          v-model="formData.username"
          placeholder="请输入用户名"
          prefixIcon="person"
          :styles="inputStyles"
        />
        <uni-easyinput
          v-model="formData.password"
          type="password"
          placeholder="请输入密码"
          prefixIcon="locked"
          :styles="inputStyles"
        />
        <button class="login-btn" @click="handleLogin">登 录</button>
      </view>

      <!-- 注册表单 -->
      <view v-else class="login-form">
        <!-- 错误信息显示 -->
        <view v-if="registerErrorMessage" class="error-message">
          <text class="error-text">{{ registerErrorMessage }}</text>
        </view>

        <uni-easyinput
          v-model="formData.username"
          placeholder="请输入用户名"
          prefixIcon="person"
          :styles="inputStyles"
        />
        <uni-easyinput
          v-model="formData.password"
          type="password"
          placeholder="请输入密码"
          prefixIcon="locked"
          :styles="inputStyles"
        />
        <uni-easyinput
          v-model="formData.confirmPassword"
          type="password"
          placeholder="再次确认密码"
          prefixIcon="locked"
          :styles="inputStyles"
        />
        <button class="login-btn" @click="handleRegister">注 册</button>
      </view>
    </view>

  </view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { authApi } from '../../api/index.js';
import { setToken, setUserInfo, validateUsername, validatePassword } from '../../utils/auth.js';

uni.setNavigationBarTitle({
	  title:'智慧大棚环境监控系统'
})

// 当前激活的选项卡
const activeTab = ref('account');

// 错误信息状态
const loginErrorMessage = ref('');
const registerErrorMessage = ref('');

// 表单数据
const formData = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  mobile: '',
  code: ''
});

// 输入框样式
const inputStyles = {
  borderColor: '#a5d6a7', // 淡绿色边框
  borderRadius: '5px'
};

// 切换选项卡函数
const switchTab = (tab) => {
  activeTab.value = tab;
  // 切换选项卡时清除错误信息
  loginErrorMessage.value = '';
  registerErrorMessage.value = '';
};

// 登录处理函数
const handleLogin = async () => {
  if (activeTab.value === 'account') {
    // 清除之前的错误信息
    loginErrorMessage.value = '';

    // 验证用户名
    const usernameValidation = validateUsername(formData.username);
    if (!usernameValidation.valid) {
      loginErrorMessage.value = usernameValidation.message;
      return;
    }

    // 验证密码
    const passwordValidation = validatePassword(formData.password);
    if (!passwordValidation.valid) {
      loginErrorMessage.value = passwordValidation.message;
      return;
    }

    // 显示加载状态
    uni.showLoading({
      title: '登录中...'
    });

    try {
      // 调用登录 API
      const response = await authApi.login(formData.username, formData.password);

      // 保存 token 和用户信息
      if (response.data && response.data.token) {
        setToken(response.data.token);
        if (response.data.userInfo) {
          setUserInfo(response.data.userInfo);
        }

        uni.hideLoading();
        uni.showToast({
          title: '登录成功',
          icon: 'success'
        });

        // 清除错误信息
        loginErrorMessage.value = '';

        // 登录成功后跳转到主页
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/weather/weather'
          });
        }, 1500);
      } else {
        throw new Error('登录响应数据格式错误');
      }
    } catch (error) {
      uni.hideLoading();
      console.error('登录失败:', error);
      console.log('错误对象详情:', JSON.stringify(error, null, 2));
      console.log('当前表单数据:', JSON.stringify(formData, null, 2));

      // 显示具体的错误信息，保留用户输入的数据
      let errorMessage = '登录失败，请检查用户名和密码';

      // 优先从error.message获取错误信息
      if (error.message) {
        errorMessage = error.message;
      }
      // 如果error.message不存在，尝试从error.data.message获取
      else if (error.data && error.data.message) {
        errorMessage = error.data.message;
      }
      // 如果error本身就是响应数据对象，直接获取message
      else if (error.code && error.message) {
        errorMessage = error.message;
      }

      loginErrorMessage.value = errorMessage;

      // 验证表单数据是否被保留
      console.log('错误处理后表单数据:', JSON.stringify(formData, null, 2));

      // 注意：不清空formData，保留用户输入的数据
      // 确保用户输入的数据不会被清空
    }
  }
};

// 注册处理函数
const handleRegister = async () => {
  // 清除之前的错误信息
  registerErrorMessage.value = '';

  // 验证用户名
  const usernameValidation = validateUsername(formData.username);
  if (!usernameValidation.valid) {
    registerErrorMessage.value = usernameValidation.message;
    return;
  }

  // 验证密码
  const passwordValidation = validatePassword(formData.password);
  if (!passwordValidation.valid) {
    registerErrorMessage.value = passwordValidation.message;
    return;
  }

  // 验证确认密码
  if (formData.password !== formData.confirmPassword) {
    registerErrorMessage.value = '两次输入的密码不一致';
    return;
  }

  // 显示加载状态
  uni.showLoading({
    title: '注册中...'
  });

  try {
    // 调用注册 API
    await authApi.register(formData.username, formData.password);

    uni.hideLoading();
    uni.showToast({
      title: '注册成功',
      icon: 'success'
    });

    // 清除错误信息
    registerErrorMessage.value = '';

    // 注册成功后切换到登录选项卡并清空表单
    activeTab.value = 'account';
    formData.username = '';
    formData.password = '';
    formData.confirmPassword = '';
  } catch (error) {
    uni.hideLoading();
    console.error('注册失败:', error);

    // 显示具体的错误信息，保留用户输入的数据
    let errorMessage = '注册失败，请稍后重试';

    // 优先从error.message获取错误信息
    if (error.message) {
      errorMessage = error.message;
    }
    // 如果error.message不存在，尝试从error.data.message获取
    else if (error.data && error.data.message) {
      errorMessage = error.data.message;
    }
    // 如果error本身就是响应数据对象，直接获取message
    else if (error.code && error.message) {
      errorMessage = error.message;
    }

    registerErrorMessage.value = errorMessage;

    // 注意：不清空formData，保留用户输入的数据
    // 确保用户输入的数据不会被清空
  }
};

</script>

<style>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  /* 使用从淡蓝色到淡绿色的渐变 */
  background: linear-gradient(135deg, #e0f7fa 0%, #e8f5e9 100%);
  padding: 40rpx;
}

.title-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 80rpx;
  margin-bottom: 2.875rem;
}

.main-title {
  /*font-size: 2.5rem;*/
  font-size: 48rpx;
  font-weight: bold;
  color: #2e7d32; /* 深绿色标题，代表植物 */
  margin-bottom: 20rpx;
}

.sub-title {
  font-size: 28rpx;
  color: #2e7d32;
}

.login-form-container {
  width: 85%;
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.login-tabs {
  display: flex;
  border-bottom: 2rpx solid #f0f0f0;
  margin-bottom: 30rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 1.1rem;
  padding-bottom: 20rpx;
  color: #999;
  position: relative;
}

.tab-item.active {
  color: #2e7d32; /* 深绿色激活选项卡文字 */
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -2rpx;
  left: 25%;
  width: 50%;
  height: 4rpx;
  background-color: #2e7d32; /* 深绿色激活选项卡下划线 */
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.error-message {
  background-color: #ffebee;
  border: 1rpx solid #f44336;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.error-text {
  color: #d32f2f;
  font-size: 28rpx;
  line-height: 1.4;
}

.verification-code-input {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.code-btn {
  width: 200rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 24rpx;
  background-color: #f0f0f0;
  color: #666;
  border: none;
}

.login-btn {
  width: 80%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #2e7d32; /* 深绿色按钮 */
  color: white;
  font-size: 32rpx;
  border-radius: 20rpx;
  margin-top: 20rpx;
  border: none;
}

.third-party-login {
  margin-top: 80rpx;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.third-party-title {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 30rpx;
}

.third-party-icons {
  display: flex;
  justify-content: center;
  gap: 60rpx;
  margin-bottom: 40rpx;
}

.icon-item {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.third-party-icon {
  width: 50rpx;
  height: 50rpx;
}

.register-tip {
  font-size: 26rpx;
  color: #999;
  display: flex;
  gap: 10rpx;
}

.register-link {
  color: #2e7d32; /* 深绿色注册链接 */
}
</style>